/*
 * @Author: huangyq
 * @Date: 2022-04-26 16:02:41
 * @LastEditTime: 2022-06-14 13:42:43
 * @LastEditors: huangyq
 * @Description: table 和分页hook
 * @FilePath: /vue3-boilerplate-pc-client/src/hooks/useTablePagination.ts
 */

import { ref, toRaw, isReactive } from 'vue'
import { IBaseRequest, IBaseResponse } from '@/plugins/httpHelper/index'
import { AxiosPromise } from 'axios'
import { paramType } from '@/interface'

export function useTablePagination(
  fetch: (params: IBaseRequest) => AxiosPromise<IBaseResponse>
) {
  const list = ref<any[]>([])
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const loading = ref(false)
  let cacheParams: paramType = {}

  /**
   * 查询数据
   */
  async function onTableSearch(
    params?: paramType,
    alias?: Record<string, string>
  ) {
    loading.value = true
    if (params) cacheParams = isReactive(params) ? toRaw(params) : params
    const res: any = await fetch({
      curPage: currentPage.value,
      pageSize: pageSize.value,
      ...cacheParams
    })

    loading.value = false
    if (res.data.success) {
      const aliasData = alias?.data ? alias.data : 'data'
      list.value = res.data[aliasData]
      currentPage.value = res.data[alias?.curPage ? alias.curPage : 'curPage']
      pageSize.value = res.data[alias?.pageSize ? alias.pageSize : 'pageSize']
      total.value = res.data[alias?.totalRows ? alias.totalRows : 'totalRows']
    } else {
      list.value = []
      currentPage.value = 1
      total.value = 0
    }
  }

  /**
   * 计算高度
   */
  const countHeight = ref(true)
  function onCountHeight() {
    countHeight.value = !countHeight.value
  }

  function onSizeChange(v: number) {
    pageSize.value = v
    onTableSearch()
  }

  function onCurrentChange(v: number) {
    currentPage.value = v
    onTableSearch()
  }

  return {
    list,
    onTableSearch,
    loading,
    currentPage,
    pageSize,
    total,
    countHeight,
    onCountHeight,
    onSizeChange,
    onCurrentChange
  }
}
